package com.fadadianqi.logistics.admin.staff.service;

import com.fadadianqi.logistics.admin.staff.dao.GroupDAO;
import com.fadadianqi.logistics.admin.staff.model.Group;
import com.fadadianqi.cache.Cache;
import com.fadadianqi.cache.CacheFactory;
import com.fadadianqi.commons.PrimaryKeyCreator;
import com.yeqiangwei.commons.util.ValidatorHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class GroupService {

    private Cache cache = CacheFactory.getCache("staff");

    private static final String KEY_PREFIX = "groups_";

    public void init() {
        List<Group> groups = findAll();
        if (ValidatorHelper.isEmpty(groups)) {
            Group g = new Group();
            g.setName("admin");
            save(g);
            groupActionService.allActionToGroup(g);
        }
    }

    public void save(Group group) {
        if (ValidatorHelper.isEmpty(group.getId())) {
            group.setId(PrimaryKeyCreator.create());
            groupDAO.create(group);
        } else {
            groupDAO.update(group);
        }
        cache.del("groups");
        cache.del("group_" + group.getId());
    }

    public Group getById(String id) {
        Group group = (Group) cache.get("group_" + id);
        if (group == null) {
            group = groupDAO.getById(id);
            if (group != null) {
                cache.set("group_" + group.getId(), group);
            }
        }
        return group;
    }

    public List<Group> findAll() {
        List<Group> gs = (List<Group>) cache.get("groups");
        if (gs != null) {
            return gs;
        }
        gs = groupDAO.findAll();
        cache.set("groups", gs);
        return gs;
    }

    @Autowired
    private GroupDAO groupDAO;

    @Autowired
    private GroupActionService groupActionService;
}
